import {
	apiBaseUrl,
	appId,
	hfKey,
} from './config.js';
import * as common from './common.js' //引入common
import * as db from './db.js' //引入common
// 需要登陆的，都写到这里，否则就是不需要登陆的接口
const methodsToken = [
	'/admin/base/login',
	'/admin/base/captcha',
	'/admin/base/send',
	'/admin/base/reg',
	'/admin/base/forgetPassword'
	
];
const post = (method, data, callback,complete) => {
	
	uni.showLoading({
		title: '加载中',
		mask:true,
	});

	uni.request({
		url: apiBaseUrl + method,
		data: data,
		header: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			"AppId":appId,
		},
		method: 'POST',
		success: (response) => {
			uni.hideLoading();
			const result = response.data
			if (!result.status) {
				// 登录信息过期或者未登录
				if (result.code === 401 ) {
					db.del("userToken");
					uni.showToast({
						title: result.msg,
						icon: 'none',
						duration: 1000,
						complete: function() {
							setTimeout(function() {
								uni.hideToast();
								let current =  getCurrentPages()
								current = current[current.length - 1]
								if (current.route.indexOf('/pages/login/login/index1') > -1 ) {
									return
								}
								uni.redirectTo({
									url: '/pages/login/login/index1'
								})
							}, 1000)
						}
					});
				}
			}
			callback(result);
		},
		complete: (response) => {
			uni.hideLoading();
			complete?complete(): "";
		},
		fail: (error) => {
			uni.showLoading({
				title: '网络开小差了',
				mask:true,
			});
			uni.hideLoading();
			if (error && error.response) {
				showError(error.response);
			} else {
				
			}
			
		},
	});
}

const postNoLoading = (method, data, callback,complete) => {
	uni.request({
		url: apiBaseUrl + method,
		data: data,
		header: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			"AppId":appId,
		},
		method: 'POST',
		success: (response) => {
			const result = response.data
			if (!result.status) {
				// 登录信息过期或者未登录
				if (result.code === 401 ) {
					db.del("userToken");
					uni.showToast({
						title: result.msg,
						icon: 'none',
						duration: 1000,
						complete: function() {
							setTimeout(function() {
								uni.hideToast();
								let current =  getCurrentPages()
								current = current[current.length - 1]
								if (current.route.indexOf('/pages/login/login/index1') > -1 ) {
									return
								}
								uni.redirectTo({
									url: '/pages/login/login/index1'
								})
							}, 1000)
						}
					});
				}
			}
			callback(result);
		},
		complete: (response) => {
			complete?complete(): "";
		},
		fail: (error) => {
			uni.showLoading({
				title: '网络开小差了',
				mask:true,
			});

			if (error && error.response) {
				showError(error.response);
			} else {
				
			}
			
		},
	});
}

//插件post
const pluginsPost = (method, data, callback) => {
	uni.showLoading({
		title: '加载中',
		mask:true,
	});

	// 判断token是否存在
	if (methodsToken.indexOf(method) >= 0) {
		// 获取用户token
		let userToken = db.get("userToken");
		if (!userToken) {
			common.jumpToLogin();
			return false;
		} else {
			data.token = userToken;
		}
	}
	uni.request({
		url: apiBaseUrl + 'plugins/' + method + '.html',
		data: data,
		header: {
			'Accept': 'application/json',
			'Content-Type': 'application/json',
			"AppId":appId,
		},
		method: 'POST',
		success: (response) => {
			uni.hideLoading();
			const result = response.data
			if (!result.status) {
				// 登录信息过期或者未登录
				if (result.data === 14007 || result.data === 14006) {
					db.del("userToken");
					uni.showToast({
						title: result.msg,
						icon: 'none',
						duration: 1000,
						mask:true,
						complete: function() {
							setTimeout(function() {
								let current =  getCurrentPages()
								current = current[current.length - 1]
								if (current.route.indexOf('pages/login/choose/index') > -1 ||  current.route.indexOf('/pages/login/login/index1') > -1 ) {
									return
								}
								uni.hideToast();
								// #ifdef H5 || APP-PLUS || APP-PLUS-NVUE
								uni.navigateTo({
									url: '/pages/login/login/index1'
								})
								// #endif
								// #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
								uni.navigateTo({
									url: '/pages/login/choose/index',
									animationType: 'pop-in',
									animationDuration: 200
								});
								// #endif
							}, 500);
						}
					});
				}
			}
			callback(result);
		},
		fail: (error) => {
			uni.hideLoading();
			if (error && error.response) {
				showError(error.response);
			}
		},
		complete: () => {
			setTimeout(function() {
				uni.hideLoading();
			}, 250);
		}
	});

}

const get = (url, callback) => {
	uni.showLoading({
		title: '加载中',
		mask:true,
	});
	uni.request({
		url: url,
		header: {
			'Accept': 'application/json',
			"AppId":appId,
		},
		method: 'GET',
		success: (response) => {
			uni.hideLoading();
			callback(response.data);
		},
		fail: (error) => {
			uni.hideLoading();
			if (error && error.response) {
				showError(error.response);
			}
		},
		complete: () => {
			setTimeout(function() {
				uni.hideLoading();
			}, 250);
		}
	});
}

const showError = error => {
	let errorMsg = ''
	switch (error.status) {
		case 400:
			errorMsg = '请求参数错误'
			break
		case 401:
			errorMsg = '未授权，请登录'
			break
		case 403:
			errorMsg = '跨域拒绝访问'
			break
		case 404:
			errorMsg = `请求地址出错: ${error.config.url}`
			break
		case 408:
			errorMsg = '请求超时'
			break
		case 500:
			errorMsg = '服务器内部错误'
			break
		case 501:
			errorMsg = '服务未实现'
			break
		case 502:
			errorMsg = '网关错误'
			break
		case 503:
			errorMsg = '服务不可用'
			break
		case 504:
			errorMsg = '网关超时'
			break
		case 505:
			errorMsg = 'HTTP版本不受支持'
			break
		default:
			errorMsg = error.msg
			break
	}

	uni.showToast({
		title: errorMsg,
		icon: 'none',
		duration: 1000,
		complete: function() {
			setTimeout(function() {
				uni.hideToast();
			}, 1000);
		}
	});
}

// 文件上传
export const uploadFiles = (callback) => {
	uni.chooseImage({
		success: (chooseImageRes) => {
			uni.showLoading({
				title: '上传中...'
			});
			const tempFilePaths = chooseImageRes.tempFilePaths;
			const uploadTask = uni.uploadFile({
				url: apiBaseUrl + 'api.html', //仅为示例，非真实的接口地址
				filePath: tempFilePaths[0],
				fileType: 'image',
				name: 'file',
				headers: {
					'Accept': 'application/json',
					'Content-Type': 'multipart/form-data',
					"AppId":appId,
				},
				formData: {
					'method': 'images.upload',
					'upfile': tempFilePaths[0]
				},
				success: (uploadFileRes) => {
					callback(JSON.parse(uploadFileRes.data));
				},
				fail: (error) => {
					if (error && error.response) {
						showError(error.response);
					}
				},
				complete: () => {
					setTimeout(function() {
						uni.hideLoading();
					}, 250);
				}
			});
		}
	});
}

// 上传图片
export const uploadImage = (num, callback) => {
	uni.chooseImage({
		count: num,
		success: (res) => {
			uni.showLoading({
				title: '上传中...'
			});
			let tempFilePaths = res.tempFilePaths
			for (var i = 0; i < tempFilePaths.length; i++) {
				uni.uploadFile({
					url: apiBaseUrl + 'api.html',
					filePath: tempFilePaths[i],
					fileType: 'image',
					name: 'file',
					headers: {
						'Accept': 'application/json',
						'Content-Type': 'multipart/form-data',
						"AppId":appId,
					},
					formData: {
						'method': 'images.upload',
						'upfile': tempFilePaths[i]
					},
					success: (uploadFileRes) => {
						callback(JSON.parse(uploadFileRes.data));
					},
					fail: (error) => {
						if (error && error.response) {
							showError(error.response);
						}
					},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					},
				});
			}
		}
	});
}

// 获取店铺配置
export const shopConfig = (callback) => get(apiBaseUrl + 'api/common/jshopconf', callback);

export const getLocation = (data,callback) => get('https://geoapi.qweather.com/v2/city/lookup?key='+ hfKey +'&location='+data.location, callback);

export const getSunInfo = (data,callback) => get('https://devapi.qweather.com/v7/astronomy/sun?key='+ hfKey +'&location='+data.location+'&date='+data.day, callback);

// 查询书目录
export const getAllClass = (data,callback) => post('/api2/getAllClass', data,callback);

export const getClassGroup = (data,callback) => post('/api2/getAllClassGroup',data, callback);
export const getLessonData = (data,callback) => post('/api2/getAllClassGroupAudio',data, callback);


//提交微信信息
export const wxInfo = (data,callback) => post('/admin/user/wxlogin',data, callback);

// 用户注册
export const reg = (data, callback) => post('/admin/base/reg', data, callback);
export const forgetPassword = (data, callback) => post('/admin/base/forgetPassword', data, callback);

export const sms = (data, callback) => post('/admin/base/send', data, callback);

// 用户登录
export const login = (data, callback) => post('/admin/base/login', data, callback);
export const changePwd = (data, callback) => post('/admin/user/changePassword', data, callback);

// 抖音解析
export const parseDyVideo = (data, callback) => get(apiBaseUrl+'/api/parseDy?'+data.param, callback);

// 游客登录
export const touristLogin = (data,callback) => post('/api/touristLogin',data, callback);

export const getShortUrl = (data,callback) => post('/api/shortUrl',data, callback);

// 转语音接口
export const ttsAudioSync = (data,callback) => post('/api/ttsAudioSync',data, callback);

// 获取所有音色
export const getAllVoice = (data,callback) => post('/api/voiceList', data,callback);

export const getSyncResult = (data,callback) => postNoLoading('/api/syncResult?key=export_tts_audio_result', data,callback);

export const getUploadToken = (data,callback) => post('/file/getUploadToken', data,callback);

export const invoiceCheck = (data,callback) => post('/api/invoice/check', data,callback);
export const invoiceSave = (data,callback) => post('/api/invoice/save', data,callback);

export const getMbtiTops = (data,callback) => post('/api/mbti/topics?key='+data, {},callback);

export const addMbtiResult = (data,callback) => post('/api/mbti/addResult', data,callback);
export const getMbtiAnswer = (data,callback) => post('/api/mbti/answer', data,callback);
